<template>
  <div>
    <h2>WebSocket 测试</h2>
    <input v-model="token" placeholder="输入令牌">
    <button @click="link">链接</button>
    <br/>
    <input type="textarea" v-model="message" placeholder="输入消息">
    <button @click="sendMessage">发送1</button>
    <button @click="sendMessage2" style="margin-left: 10px">发送2</button>
    <br/>
    接收消息：
    <div style="border: white 1px solid">
      <template v-for="(msg, index) in messageList">
        {{ msg.time }}:{{ msg.content }}<br>
      </template>
    </div>
    <ul>
      <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
    </ul>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'

const message = ref('')
const token = ref('')
const messages = ref([])
const messageList = reactive([])
const ws = ref(null)

function link() {
  ws.value = new WebSocket('ws://127.0.0.1:8080/ws?ks-sample-token=' + token.value)
  ws.value.onopen = () => {
    console.log('WebSocket 连接已建立')
  }

  ws.value.onmessage = (event) => {
    console.log('WebSocket 收到消息:' + event.data)
    const now = new Date();
    const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
    messageList.push({
      time: timeStr,
      content: event.data
    });
  }
}

function sendMessage() {
  if (message.value) {
    let json = {
      // 消息类型
      type: 'demo-message-send',
      // 消息内容，对应的实体结构
      content: JSON.stringify({
        text: message.value,
      }),
    }
    console.log('发送 WebSocket 消息:' + JSON.stringify(json))
    ws.value.send(JSON.stringify(json))
    message.value = ''
  }
}

function sendMessage2() {
  if (message.value) {
    const formData = new URLSearchParams();
    formData.append('message', message.value);

    fetch('http://localhost:8080/message/send', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'ks-sample-token': token.value
      },
      body: formData.toString()
    }).then(response => {
      if (response.ok) {
        console.log('消息发送成功');
      } else {
        console.error('消息发送失败');
      }
    }).catch(error => {
      console.error('请求异常:', error);
    });

    message.value = '';
  }
}
</script>
